package DiningPhilosophersProblem1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2022-12-28
 * Time: 8:26
 */

public class Philosophers extends Thread{
    private Chopstick left;//左手筷子
    private Chopstick right;//右手筷子

    public Philosophers(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while(true) {
            //尝试左手拿筷子
            if(left.tryLock()) {
                try{
                    //尝试右手拿筷子
                    if(right.tryLock()) {
                        try {
                            eat();
                        }finally {
                            right.unlock();
                        }
                    }
                }finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() {
        System.out.println(Thread.currentThread() + "eating...");
        try {
            Thread.sleep(1000);//思考1s钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}